<?php


namespace app\community\controller;


use app\common\controller\Together;
use app\common\controller\Common;
use app\index\controller\Base;
use think\Db;
use think\Exception;
use think\Session;
use think\Validate;

class Volunteers extends Base
{

    //志愿者列表
    public function index()
    {
        $keyword = '';
        $where = [];
        if (!empty($_GET['keyword'])) {
            $keyword = $_GET['keyword'];
            $where['a.name'] = ['like', "%{$keyword}%"];
        }
        $thisWechat = Session::get("thisWechat");
        $where['b.uniacid'] = $thisWechat['id'];


        if (!empty($_GET['type'])) {
            try {
                $page = empty($_GET['page']) ? 1 : $_GET['page'];
                $limit = empty($_GET['limit']) ? 10 : $_GET['limit'];
                $start = ($page - 1) * $limit;

                $list = Db::name("community_registration")->alias("a")
                    ->join("community_colony b", "a.colony_id = b.id")
                    ->join("admin_fans c","a.fans_id = c.id")
                    ->where($where)->field("a.*,b.name colony_name,c.nickname")->limit($start,$limit)->select();
                $count = Db::name("community_registration")->alias("a")
                    ->join("community_colony b", "a.colony_id = b.id")
                    ->join("admin_fans c","a.fans_id = c.id")
                    ->where($where)->count();
                //审核状态
                $audit = Db::name("config_attribute")->where(['key' => "audit"])->value("value");
                $audit = explode("|", $audit);
                foreach ($audit as $k => $v) {
                    $audit[$k + 1] = $v;
                }
                unset($audit[0]);

                $sex = Db::name("config_attribute")->where(['key' => "sex"])->value("value");
                $sex = explode("|", $sex);
                foreach ($sex as $k => $v) {
                    $sex[$k + 1] = $v;
                }
                unset($sex[0]);

                foreach ($list as $k => $v) {
                    $list[$k]['sex'] = $sex[$v['sex']];
                    $list[$k]['addtime'] = date("Y-m-d H:i:s",$v['addtime']);
                }
                $black['code'] = 0;
                $black['data'] = $list;
                $black['count'] = $count;
            } catch (Exception $e) {
                $black['code'] = 202;
                $black['msg'] = $e->getMessage();
            }
            return $black;
        }

        $assign = [
            'keyword' => $keyword,
        ];
        $this->assign($assign);
        return $this->fetch('index');
    }

    //充值操作
    public function changes(){
        $type = $_POST['type'];
        $id = $_POST['id'];
        $common = new Common();
        try{
            $status = $_POST['status']; //操作
            $number = $_POST['number']; //数量
            $remark = empty($_POST['remark'])?'':$_POST['remark']; //备注

            $integral = Db::name("community_registration")->where(['id'=>$id])->value("integral");
            if($number<0){
                throw new Exception("非法操作");
            }
            if($status==2){
                if($integral - $number<0){ throw new Exception("非法操作");}
                Db::name("community_registration")->where(['id'=>$id])->setDec("integral",$number);
                $after_number = $integral-$number;
                $log['remark'] = "用户【" . Session::get("user_name") . "】操作志愿者积分,积分减少【".$number."】,操作志愿者id【".$id."】";
            }elseif ($status==1){
                Db::name("community_registration")->where(['id'=>$id])->setInc("integral",$number);
                $log['remark'] = "用户【" . Session::get("user_name") . "】操作志愿者积分,积分增加【".$number."】,操作志愿者id【".$id."】";
                $after_number = $integral+$number;
            }else{
                Db::name("community_registration")->where(['id'=>$id])->update(['integral'=>$number]);
                $log['remark'] = "用户【" . Session::get("user_name") . "】操作志愿者积分,最终积分【".$number."】,操作志愿者id【".$id."】";
                $after_number = $number;
            }


            //记录日志
            $data['remark'] = $remark;
            $data['reg_id'] = $id;
            $data['type'] = "integral";
            $data['type_status'] = $status;
            $data['number'] = $number;
            $data['before_number'] = $integral;
            $data['after_number'] = $after_number;
            $data['addtime'] = time();
            $data['operator_id'] = Session::get("id");
            $data['auto'] =  Session::get("auto");
            Db::name("community_registration_log")->insert($data);


            //记录操作日志
            $log['controller'] = "Volunteers";
            $log['methods'] = "changes";
            $common->addLog($log);

            $black['code'] = 0;
            $black['msg'] = "操作成功";
        }catch (Exception $e){
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return $black;

    }


    //积分明细
    public function integralLog(){
        $where = [];

        if(empty($_GET['id'])){
            throw new Exception("非法操作");
        }
        $id = $_GET['id'];
        $this->assign('id',$id);
        $where['a.reg_id'] = $_GET['id'];


        if(!empty($_GET['type'])){
            try {
                $page = empty($_GET['page']) ? 1 : $_GET['page'];
                $limit = empty($_GET['limit']) ? 10 : $_GET['limit'];
                $start = ($page - 1) * $limit;
                $list = Db::name("community_registration_log")->alias("a")
                    ->join("community_registration b","a.reg_id = b.id")
                    ->field("a.*,b.name")
                    ->where($where)->limit($start,$limit)
                    ->order("a.id desc")
                    ->select();

                $type_status = [1=>"增加",2=>"减少",3=>"管理员设置"];
                foreach ($list as $k=>$v){
                    $list[$k]['status'] = $type_status[$v['type_status']];
                    $list[$k]['type'] = "积分";
                    $list[$k]['addtime'] = date("Y-m-d H:i:s",$v['addtime']);
                }

                $count = Db::name("community_registration_log")->alias("a")
                    ->join("community_registration b","a.reg_id = b.id")
                    ->where($where)->count("*");

                $black['code'] = 0;
                $black['data'] = $list;
                $black['count'] = $count;
            }catch (Exception $e){
                $black['code'] = 202;
                $black['msg'] = $e->getMessage();
            }
            return $black;
        }

        return $this->fetch('log');
    }


    //添加、详情视图
    public function addData()
    {
        //审核状态
        $audit = Db::name("config_attribute")->where(['key' => "audit"])->value("value");
        $audit = explode("|", $audit);
        foreach ($audit as $k => $v) {
            $audit[$k + 1] = $v;
        }
        unset($audit[0]);

        //性别
        $sex = Db::name("config_attribute")->where(['key' => "sex"])->value("value");
        $sex = explode("|", $sex);
        foreach ($sex as $k => $v) {
            $sex[$k + 1] = $v;
        }
        unset($sex[0]);

        //身体状况
        $condition = Db::name("config_attribute")->where(['key' => "condition"])->value("value");
        $condition = explode("|", $condition);
        foreach ($condition as $k => $v) {
            $condition[$k + 1] = $v;
        }
        unset($condition[0]);

        //学历
        $schooling = Db::name("config_attribute")->where(['key' => "schooling"])->value("value");
        $schooling = explode("|", $schooling);
        foreach ($schooling as $k => $v) {
            $schooling[$k + 1] = $v;
        }
        unset($schooling[0]);

        //义工类型
        $volunteers = Db::name("config_attribute")->where(['key' => "volunteers"])->value("value");
        $volunteers = explode("|", $volunteers);
        foreach ($volunteers as $k => $v) {
            $volunteers[$k + 1] = $v;
        }
        unset($volunteers[0]);

        //获取所管理的景区
        //获取管理的景区
        $Together = new Together();
        $colony = $Together->findColony();
        $this->assign("colony", $colony);


        $assign = [
            "audit" => $audit,
            "sex" => $sex,
            "condition" => $condition,
            "schooling" => $schooling,
            "volunteers" => $volunteers
        ];
        $this->assign($assign);

        //志愿者详细信息
        if (!empty($_GET['id'])) {
            $id = $_GET['id'];
            $detail = Db::name("community_registration")->alias("a")
                ->join("admin_fans b", "a.fans_id = b.id")
                ->where(['a.id' => $id])->field("a.*,b.realName")
                ->find();

            $this->assign("detail", $detail);
            return $this->fetch('editData');
        } else {
            return $this->fetch('addData');
        }
    }

    //添加、修改操作
    public function doData()
    {
        $common = new Common();
        Db::startTrans();
        try {

            $rule = [
                ["fans_id", "require", "请关联粉丝"],
                ["colony_id", "require", "请选择所属景区"],

                ["name", "require", "请输入姓名"],
                ["place", "require", "请输入所在籍贯"],
                ["idcard", "require", "请输入身份证号"],
                ["work_units", "require", "请输入工作单位"],
                ["mobile", "require", "请输入联系方式"],
                ["weight", "require", "请输入体重"],
                ["height", "require", "请输入身高"],
            ];
            $validate = new Validate($rule);
            $value = $this->request->post();
            if (!$validate->check($value)) {
                throw new Exception($validate->getError());
            }


            //判断该志愿者在对应景区是否填表
            $where['fans_id'] = $value['fans_id'];
            $where['colony_id'] = $value['colony_id'];
//            $where['community_id'] = $value['community_id'];
            if (!empty($value['id'])) {
                $where['id'] = ['neq', $value['id']];
            }
            $detail = Db::name("community_registration")->where($where)->value("id");
            if (!empty($detail)) {
                throw new Exception("该粉丝已经是该景区的志愿者，无需重复添加");
            }

            if (!empty($value['idcard'])) {
                if (!$common->setCard($value['idcard'])) {
                    throw new Exception("身份证号格式有误");
                }
            }
            if (!empty($value['mobile'])) {
                if (!$common->isMobile($value['mobile'])) {
                    throw new Exception("手机号格式有误");
                }
            }

            //执行添加操作
            if (empty($value['id'])) {
                $value['addtime'] = time();
                $value['add_id'] = Session::get("id");
                $id = Db::name("community_registration")->insertGetId($value);
                $log['remark'] = "用户【" . Session::get("user_name") . "】录入志愿者信息,志愿者id【" . $id . "】";
            } else {
                $id = $value['id'];
                $value['updatetime'] = time();
                $value['update_id'] = Session::get("id");
                Db::name("community_registration")->update($value);
                $log['remark'] = "用户【" . Session::get("user_name") . "】更新志愿者信息,志愿者id【" . $id . "】";
            }


            $log['controller'] = "Volunteers";
            $log['methods'] = "doData";
            $common->addLog($log);

            $black['code'] = 0;
            $black['msg'] = "添加成功";
            Db::commit();
        } catch (Exception $e) {
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
            Db::rollback();
        }
        return $black;
    }

    //删除操作
    public function delData()
    {
        $common = new Common();
        Db::startTrans();
        try {
            $id = $_POST['id'];
            $navList = Db::name("community_registration")->where(['id' => ['in', $id]])->field("id,name")->select();
            $navList = array_column($navList, "id");
            $navList = implode($navList, ",");
            $log['remark'] = "账号【" . Session::get("user_name") . "】删除志愿者信息,删除id【" . $navList . "】";
            $log['controller'] = "Volunteers";
            $log['methods'] = "delData";
            $common->addLog($log);
            Db::name("community_registration")->where(['id' => ['in', $id]])->delete();


            $black['code'] = 0;
            $black['msg'] = "删除成功";
            Db::commit();
        } catch (Exception $e) {
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
            Db::rollback();
        }
        return $black;
    }

}